<template>
  <div class="app-container">
    <div class="search-container">
      <el-form :model="searchParam" :inline="true" label-width="80px">
        <!-- <el-form-item label="设备种类">
          <el-tree-select
            clearable
            @keyup.enter="search"
            placeholder="请选择设备种类"
            v-model="searchParam.assetTypeId"
            :data="deviceTypeList"
            node-key="id"
            :props="{
              label: 'assetTypeName',
              value: 'id',
              children: 'nodes',
            }"
            :render-after-expand="false"
            :check-strictly="true"
          />
        </el-form-item> -->
        <!-- <el-form-item label="维护类型">
          <el-select
            v-model="searchParam.inspectionPlanld"
            placeholder="请选择维护类型"
            clearable
          >
            <el-option
              v-for="item in inspectionPlanList"
              :key="`${item.id}`"
              :label="`${item.planName}`"
              :value="`${item.id}`"
            />
          </el-select>
        </el-form-item> -->

        <el-form-item label="维护类型">
          <el-select
            v-model="searchParam.sopTypeId"
            placeholder="请选择维护类型"
            clearable
            style="width: 100%"
          >
            <el-option
              v-for="item in typeList"
              :key="item.id"
              :label="item.sopTypeName"
              :value="item.id"
            />
          </el-select>
        </el-form-item>

        <!-- <el-form-item label="维护部门">
          <SelectOriganizationDangerGrant
            @change-data="(datas) => getSelectDatas(datas, '维护部门')"
            :isCheckStrictly="true"
            :isMultiple="false"
            :disabled="false"
            :data="dataObject('维护部门')"
            :selectData="searchParam.executeDepartmentId"
          />
        </el-form-item> -->

        <el-form-item label="维护班组" prop="executeTeamld">
          <el-select
            v-model="searchParam.executeTeamld"
            placeholder="请选择维护班组"
            clearable
          >
            <el-option
              v-for="item in crewList"
              :key="`${item.id}`"
              :label="`${item.teamName}`"
              :value="`${item.id}`"
            />
          </el-select>
        </el-form-item>

        <!-- <el-form-item label="设备管理部门">
          <SelectOriganizationDangerGrant
            @change-data="(datas) => getSelectDatas(datas, '设备管理部门')"
            :isCheckStrictly="true"
            :isMultiple="false"
            :disabled="false"
            :data="dataObject('设备管理部门')"
            :selectData="searchParam.assetDepartmentId"
          />
        </el-form-item> -->

        <el-form-item label="计划名称">
          <el-input
            v-model="searchParam.planName"
            placeholder="请输入计划名称"
            clearable
            @keyup.enter="search"
          />
        </el-form-item>
        <el-form-item label="作业区域" prop="locationId">
          <el-tree-select
            placeholder="请输入作业区域"
            filterable
            v-model="searchParam.locationId"
            :data="locationInfoTree"
            node-key="id"
            clearable
            :props="{ label: 'locationName', children: 'nodes' }"
            check-strictly
            :render-after-expand="false"
          />
        </el-form-item>
        <el-form-item label="维护状态">
          <el-select
            v-model="searchParam.enabled"
            placeholder="请选择维护状态"
            clearable
          >
            <el-option
              v-for="item in useDictionary('Enabled')"
              :key="item.value"
              :label="item.label"
              :value="Number(item.value)"
            />
          </el-select>
        </el-form-item>
        <!-- <el-form-item label="维护时间">
          <el-date-picker
            v-model="searchParam.inspectionDateSearch"
            type="datetimerange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="YYYY-MM-DD HH:mm:ss"
            @change="getcreateTime"
          />
        </el-form-item> -->
        <el-form-item>
          <el-button type="primary" @click="search"
            ><i-ep-search />搜索</el-button
          >
          <el-button @click="reset"><i-ep-refresh />重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <el-card shadow="never" class="table-container">
      <template #header>
        <el-button type="success" plain @click="openDialog()">
          <i-ep-plus />
          新增
        </el-button>
        <el-button
          type="danger"
          plain
          :disabled="ids.length === 0"
          @click="handleTableDelete()"
        >
          <i-ep-delete />
          删除
        </el-button>
      </template>

      <el-table
        ref="dataTableRef"
        v-loading="loading"
        :data="tableData"
        highlight-current-row
        border
        @selection-change="handleSelectionChange"
        @sort-change="onTableSortChanged"
      >
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column
          label="计划编号"
          prop="planNo"
          min-width="150"
          show-overflow-tooltip
          sortable
        />
        <el-table-column
          label="计划名称"
          prop="planName"
          min-width="220"
          show-overflow-tooltip
          sortable
        />
        <el-table-column
          label="作业区域"
          prop="locationName"
          min-width="150"
          show-overflow-tooltip
          align="center"
        />
        <el-table-column
          label="维护类型"
          prop="sopTypeName"
          min-width="220"
          show-overflow-tooltip
          sortable
        />
        <el-table-column
          label="维护周期"
          prop="taskPeriod"
          min-width="120"
          align="right"
          show-overflow-tooltip
          sortable
        >
          <template #default="scope">
            {{ scope.row.taskPeriod }}
            {{ useDictionary("TaskPeriodUnit", scope.row.taskPeriodUnit) }}
          </template>
        </el-table-column>

        <el-table-column
          label="执行提醒时间"
          prop="taskPeriod"
          min-width="120"
          align="right"
          show-overflow-tooltip
        >
          <template #default="scope">
            {{ scope.row.taskRemindTime }}
            {{ useDictionary("reminderTime", scope.row.remindTimeUnit) }}
          </template>
        </el-table-column>
        <el-table-column
          label="到期提醒时间"
          prop="expirationReminderTime"
          min-width="150"
          align="center"
          show-overflow-tooltip
        >
          <template #default="scope">
            {{ scope.row.expirationReminderTime }}
            {{ useDictionary("reminderTime", scope.row.expirationReminderTimeUnit) }}
          </template>
        </el-table-column>
        <el-table-column
          label="计划起始日期"
          prop="planStartDate"
          min-width="150"
          show-overflow-tooltip
          align="center"
          sortable
        >
          <template #default="scope">
            {{ dayjs(scope.row.planStartDate).format("YYYY-MM-DD") }}
          </template>
        </el-table-column>
        <el-table-column
          label="计划截止日期"
          prop="planEndDate"
          min-width="150"
          align="center"
          show-overflow-tooltip
          sortable
        >
          <template #default="scope">
            {{ dayjs(scope.row.planEndDate).format("YYYY-MM-DD") }}
          </template>
        </el-table-column>
        <!-- <el-table-column
          label="维护路线"
          prop="inspectionRouteName"
          min-width="100"
          show-overflow-tooltip
          align="center"
        /> -->
        <!-- <el-table-column
          label="维护部门"
          prop="executeDepartmentName"
          min-width="100"
          show-overflow-tooltip
          align="center"
        /> -->
        <!-- <el-table-column
          label="维护班组"
          prop="executeTeamName"
          min-width="200"
          show-overflow-tooltip
          align="center"
        /> -->
        <el-table-column
          label="维护班组"
          min-width="200"
          show-overflow-tooltip
          align="center"
          prop="executeTeamName"
          sortable
        />

        <el-table-column
          label="计划状态"
          prop="enabled"
          min-width="120"
          show-overflow-tooltip
          align="center"
          sortable
        >
          <template #default="scope">
            <el-tag type="success" v-if="scope.row.enabled === 1">启用</el-tag>
            <el-tag type="info" v-else>停用</el-tag>
          </template>
        </el-table-column>
        <el-table-column fixed="right" label="操作" width="400" align="center">
          <template #default="scope">
            <el-button
              type="primary"
              size="small"
              link
              @click="openDialogdetail(scope.row)"
            >
              <i-ep-search />
              查看
            </el-button>
            <el-button
              type="primary"
              size="small"
              link
              @click="openBuildDialog(scope.row)"
            >
              <i-ep-position />
              生成维护任务
            </el-button>
            <el-button
              type="primary"
              size="small"
              disabled
              link
              @click="openDialogdetail(scope.row)"
            >
              <i-ep-search />
              维护记录
            </el-button>
            <el-button
              type="primary"
              size="small"
              link
              @click="openDialog(scope.row)"
            >
              <i-ep-edit />
              编辑
            </el-button>
            <el-button
              type="primary"
              size="small"
              link
              @click="deleteItem(scope.row.id)"
            >
              <i-ep-delete />
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <el-pagination
        :background="true"
        :current-page="pageable.pageNum"
        :page-size="pageable.pageSize"
        :page-sizes="[10, 25, 50, 100]"
        :total="pageable.total"
        layout="total, sizes, prev, pager, next, jumper"
        class="mt-[20px]"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </el-card>

    <eamMaintainPlan-edit
      :visible="addDialog.visible"
      :title="addDialog.title"
      :data="addDialog.data"
      @reset-table="(id:string) => (id?.length ? getTableList() : getTableList())"
      :is-readonly="addDialog.readvisible"
      @change-visible="changeVisible"
    />
    <eamMaintainPlan-build
      v-model:visible="buildDialog.visible"
      :id="buildDialog.id"
      @echo-info="changeBuildVisible"
    />
  </div>
</template>

<script setup lang="ts">
import { useTable, useDictionary } from "@/utils/useTable";
import request from "@/utils/request";
import { useDictStoreHook } from "@/store/modules/dictionary"; // 引入
const dictionaryStore = useDictStoreHook();
import { filterOrder } from "@/utils/commonHooks";
import { getCrewListApi } from "@/utils/commonData";
import { useRoute } from "vue-router";
import {
  getStandardTypesApi,
  getStandardDevicesApi,
  getMakerListApi,
  getBrandModelListApi,
} from "@/utils/commonData";
import dayjs from "dayjs";
defineOptions({
  name: "EAMEQUMAINTAINPLAN",
  inheritAttrs: false,
});

// 请求参数
const requestApi = "/eam/equMaintainPlan/queryByPage";

// 是否需要分页
const pagination = true;

const initParam = reactive({
  sort: {
    column: "",
    orderBy: "",
  },
});

// 初始化搜索参数数据
const searchParamInit = {
  assetTypeId: "", // 设备种类
  sopTypeId: "", // 维护类型
  executeTeamld: "", // 维护班组
  assetDepartmentId: "", // 设备管理部门
  executeDepartmentId: "", // 维护部门
  planName: "", // 计划信息
  enabled: "", // 维护状态
  // inspectionStartDate: "",
  // inspectionEndDate: "",
  // inspectionDateSearch: [],
};

const deleteParam = {
  api: "/eam/equMaintainPlan/delete",
  data: {},
};

// 数据请求错误后处理
function requestError() {}

const dataCallBack = ref(undefined); // 无需二次数据处理&不传赞数也行

// 表格操作 Hooks
const {
  tableData,
  pageable,
  searchParam,
  ids,
  getTableList,
  search,
  reset,
  handleSizeChange,
  handleCurrentChange,
  handleSelectionChange,
  handleTableDelete,
  loading,
}: any = useTable(
  requestApi,
  initParam,
  searchParamInit,
  pagination,
  dataCallBack.value,
  requestError,
  deleteParam
);

// 排序
// 监听表格排序方法
function onTableSortChanged(column: any) {
  const { prop, order } = column;
  console.log(prop, order);

  initParam.sort = {
    column: prop,
    orderBy: filterOrder(order),
  };
}
// 监听页面 initParam 改化，重新获取表格数据
watch(() => initParam, getTableList, { deep: true });

const addDialog = reactive<DialogOption>({
  visible: false,
  readvisible: false,
  title: "",
  data: {},
});

function filterPlanTeams(arr) {
  if (arr && arr.length) {
    let arrName: any = [];
    arr.map((item) => {
      arrName.push(item.teamName);
    });
    return arrName.join(",");
  } else {
    return "";
  }
}

// 查询详情
async function getInfo(id: string) {
  await request({
    url: `eam/equMaintainPlan/get/${id}`,
    method: "get",
  })
    .then((data) => {
      console.log(data.data);
      addDialog.data = data.data;
      addDialog.visible = true;
    })
    .catch((res) => {
      console.log(res);
    });
}

/** 打开问题二级分类表单弹窗 */
function openDialog(roleObj?: Object) {
  if (roleObj) {
    addDialog.title = "修改维护计划";
    getInfo(roleObj.id);
  } else {
    addDialog.title = "新增维护计划";
    addDialog.visible = true;
  }
  addDialog.readvisible = false;
}

/** 打开维护计划表单弹窗 详情 */
function openDialogdetail(roleObj?: any) {
  addDialog.title = "维护计划详情";
  getInfo(roleObj.id);
  addDialog.readvisible = true;
}

function changeVisible(value: boolean) {
  addDialog.visible = value;
  if (!value) {
    addDialog.data = {};
  }
}

async function deleteItem(id: any) {
  ElMessageBox.confirm("确认删除已选中的数据项?", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(async () => {
    await request({
      url: `/eam/equMaintainPlan/deleteItem/${id}`,
      method: "post",
    }).then((res) => {
      ElMessage.success("删除成功");
      search();
    });
  });
}

function getcreateTime(data: any) {
  if (data) {
    searchParam.value.inspectionStartDate = data[0];
    searchParam.value.inspectionEndDate = data[1];
  } else {
    searchParam.value.inspectionStartDate = "";
    searchParam.value.inspectionEndDate = "";
  }
}

// async function deleteItem(id: any) {
//   ElMessageBox.confirm("确认删除该数据项?", "警告", {
//     confirmButtonText: "确定",
//     cancelButtonText: "取消",
//     type: "warning",
//   }).then(async () => {
//     await request({
//       url: `/qms/qmsexceptionsubtype/deleteItem/${id}`,
//       method: "post",
//     }).then((res) => {
//       ElMessage.success("删除成功！");
//       search();
//     });
//   });
// }

// async function handleTableStop(id: any) {
//   if (id) {
//     ElMessageBox.confirm("确认停用该数据项?", "警告", {
//       confirmButtonText: "确定",
//       cancelButtonText: "取消",
//       type: "warning",
//     }).then(async () => {
//       await request({
//         url: `/qms/qmsexceptionsubtype/stopUsing`,
//         method: "post",
//         data: { ids: [id] },
//       }).then((res) => {
//         ElMessage.success("停用成功！");
//         search();
//       });
//     });
//   } else {
//     ElMessageBox.confirm("确认停用已选中的数据项?", "警告", {
//       confirmButtonText: "确定",
//       cancelButtonText: "取消",
//       type: "warning",
//     }).then(async () => {
//       await request({
//         url: `/qms/qmsexceptionsubtype/stopUsing`,
//         method: "post",
//         data: { ids: ids.value },
//       }).then((res) => {
//         ElMessage.success("停用成功！");
//         search();
//       });
//     });
//   }
// }

// 获取维护类型列表
const inspectionPlanList = ref([]);
const getInspectionPlanList = async () => {
  await request({
    url: "/eam/equMaintainPlan/getList",
    method: "post",
    data: {},
  }).then((res) => {
    inspectionPlanList.value = res.data;
  });
};
// 获取维护班组列表
const crewList = ref(<any>[]);
async function getCrews() {
  crewList.value = (await getCrewListApi({ teamType: "1" })) || [];
}

// 获取作业类型列表
const typeList = ref(<any>[]);
async function getTypeList(value: string) {
  const params = {
    taskKind: value,
    assetKind: 1,
  };
  typeList.value = (await getStandardTypesApi(params)) ?? [];
}

// 获取设备种类
const deviceTypeList: any = ref([]);
const getDeviceTypeList = async () => {
  await request({
    url: "eam/eamCommon/getAvailableTree",
    method: "POST",
    data: { assetKind: 1 },
  }).then((res) => {
    deviceTypeList.value = res.data;
  });
};

/** 选择组织机构并赋值Name   start **/
function getSelectDatas(datas: any, item: any) {
  if (item == "设备管理部门") {
    searchParam.value.assetDepartmentId = datas.id ? datas.id : "";
  }
  if (item == "维护部门") {
    searchParam.value.executeDepartmentId = datas.id ? datas.id : "";
  }
}

// 组织机构 placeholder值
const dataObject = (item: string) => {
  return {
    name:
      item == "管理部门"
        ? "管理部门"
        : item == "维护部门"
        ? "维护部门"
        : "设备管理部门",
    defaultProps: {
      children: "nodes",
      label: "organizationName",
      value: "id",
    },
    api: "/system/sysOrganization/getUsableTree",
  };
};

// 定义生成点检单弹窗
const buildDialog = reactive<DialogOption>({
  visible: false,
  id: "",
});

// 打开生成点检单弹窗
function openBuildDialog(roleObj?: any) {
  if (roleObj) {
    buildDialog.visible = true;
    buildDialog.id = roleObj.id;
  }
}

function changeBuildVisible() {}

onMounted(() => {
  getTableList();
  // 获取设备种类
  getDeviceTypeList();
  // 维护类型
  getInspectionPlanList();
  // 获取班组
  getCrews();
  // 作业类型列表
  getTypeList("3");
  getLocationInfoTree();
});

const route = useRoute();

watch(
  () => route,
  (newVal: any) => {
    if (route.query.taskName) {
      searchParam.value.sopTypeId = route.query.sopTypeId;
      searchParam.value.planName = route.query.taskName;
      getTableList();
    }
  },
  {
    deep: true,
    immediate: true,
  }
);
// 获取位置信息下拉树
const locationInfoTree = ref([]);
const getLocationInfoTree = async () => {
  const { data } = await request({
    url: "/eam/locationInfo/getTree",
    method: "POST",
    data: {
      enabled: 1,
    },
  });
  locationInfoTree.value = data;
};
</script>
